package com.admin.oauth.component;

import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.admin.common.utils.StringUtils;
import com.admin.oauth.constant.CacheConstant;
import com.admin.oauth.dto.OnlineUserDto;
import com.admin.component.redis.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author sq-lan
 */
@Component
@Slf4j
@AllArgsConstructor
public class OnlineUserComponent {

    private final RedisUtils redisUtils;

    /**
     * 分页查询
     *
     * @param username /
     * @param pageable /
     * @return /
     */
    public PageResult<OnlineUserDto> list(String username, Pageable pageable) {
        List<OnlineUserDto> list = list(username);
        return PageUtil.toPage(
                PageUtil.paging(pageable.getPageNumber(), pageable.getPageSize(), list),
                list.size()
        );
    }

    /**
     * 查询
     *
     * @param username /
     * @return /
     */
    public List<OnlineUserDto> list(String username) {
        String loginKey = CacheConstant.CACHE_KEY_ONLINE_USER + (StringUtils.isBlank(username) ? "" : "*" + username);
        List<String> keys = redisUtils.scan(loginKey + "*");
        Collections.reverse(keys);
        List<OnlineUserDto> list = new ArrayList<>();
        for (String key : keys) {
            list.add((OnlineUserDto) redisUtils.get(key));
        }
        list.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
        return list;
    }

}
